﻿using System;
using FireStarterModeller.BO;
using Habanero.Base.Exceptions;
using Habanero.BO.ClassDefinition;
using Habanero.Faces.Base;
using Habanero.Faces.Win;

namespace FireStarterModeller.UI.LookupLists
{
    public class SimpleLookupListControl : UserControlWin, ILookupListControl
    {
        public IControlFactory ControlFactory { get; set; }
        private DMProperty _property;
        private DMLookupListSimple _lookupList;
        private readonly IEditableGridControl _editableGridControl;
        const string _simple = "Simple";

        public SimpleLookupListControl(IControlFactory controlFactory)
        {
            if (controlFactory == null) throw new ArgumentNullException("controlFactory");
            ControlFactory = controlFactory;
            _editableGridControl = controlFactory.CreateEditableGridControl();
            _editableGridControl.Initialise(ClassDef.Get<DMListItem>());
            _editableGridControl.Buttons.Visible = false;
            BorderLayoutManager borderLayoutManager = controlFactory.CreateBorderLayoutManager(this);
            borderLayoutManager.AddControl(_editableGridControl, BorderLayoutManager.Position.Centre);
        }

        public DMProperty Property
        {
            get { return _property; }
            set
            {
                _property = value;
                bool hasProperty = _property != null;
                if (hasProperty)
                {
                    DMLookupList lookupList = _property.LookupList;
                    _lookupList = lookupList is DMLookupListSimple ? (DMLookupListSimple)lookupList : new DMLookupListSimple();
                    _editableGridControl.BusinessObjectCollection = _lookupList.ListItems;
                } else
                {
                    _lookupList = null;
                }
                _editableGridControl.Enabled = hasProperty;
            }
        }

        public DMLookupList LookupList
        {
            get { return _lookupList; }
        }

        public string LookupTypeName
        {
            get { return _simple; }
        }
    }
}
